package com.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 */
@Slf4j
@Component
public class RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private RedisTemplate<String, Object> redisObjectTemplate;
    @Autowired
    private RedisTemplate<Object, Object> objectTemplate;

    public Boolean hasKey(String key) {
        return this.redisTemplate.hasKey(key);
    }

    public String get(String key) {
        String message;
        if (hasKey(key)) {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            message = valueOperations.get();
        } else {
            message = null;
        }
        return message;
    }

    public void put(String key, String value) {
        if (!hasKey(key)) {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            valueOperations.set(value);
        } else {
            this.update(key, value);
        }

    }

    public void put(String key, Object value) {
        if (!hasKey(key)) {
            BoundValueOperations<String, Object> valueOperations = this.redisObjectTemplate.boundValueOps(key);
            valueOperations.set(value);
        } else {
            this.update(key, value);
        }

    }

    public void put(String key, String value, Long expireTime, TimeUnit timeUnit) {
        if (!hasKey(key)) {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            valueOperations.set(value);
            if (null != timeUnit) {
                valueOperations.expire(expireTime, timeUnit);
            }

        } else {
            this.update(key, value, expireTime, timeUnit);
        }
    }

    public void put(String key, String value, Date date) {
        if (!hasKey(key)) {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            valueOperations.set(value);
            if(null != date){
                valueOperations.expireAt(date);
            }
        } else {
            this.update(key, value, date);
        }
    }

    public void remove(String key) {
        if (hasKey(key)) {
            this.redisTemplate.delete(key);
        }
    }

    public void update(String key, String value) {
        BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
        valueOperations.set(value);
    }

    public void update(String key, Object value ) {
        BoundValueOperations<String, Object> valueOperations = this.redisObjectTemplate.boundValueOps(key);
        valueOperations.set(value);
    }

    public void update(String key, String value, Long expireTime, TimeUnit timeUnit) {
        BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
        valueOperations.set(value);
        if (null != timeUnit)
            valueOperations.expire(expireTime, timeUnit);
    }

    public void update(String key, String value, Date date) {
        BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
        valueOperations.set(value);
        if (null != date)
            valueOperations.expireAt(date);
    }

    public void incr(String key) {
        BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
        valueOperations.increment(1);
    }

    /**
     * 设置锁
     *
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     * @param timeout    timeout的时间范围内轮询锁, 单位: 秒
     * @return
     */
    public boolean lock(String key, String value, Long expireTime, TimeUnit timeUnit, Long timeout) {
        long beginTime = System.currentTimeMillis();
        if (timeout == 0) {
            timeout = 600L;
        }
        timeout = TimeUnit.SECONDS.toMillis(timeout);
        try {
            BoundValueOperations<String, String> valueOperations = this.redisTemplate.boundValueOps(key);
            while (System.currentTimeMillis() - beginTime < timeout) {
                Boolean aBoolean = valueOperations.setIfAbsent(value);
                //此三个参数的方法  redis版本号升级到  2.3.3使用
                //Boolean aBoolean = valueOperations.setIfAbsent(value, expireTime, timeUnit);
                if (aBoolean != null && aBoolean) {
                    valueOperations.expire(expireTime, timeUnit);
                    return true;
                }
                Thread.sleep(50, new Random().nextInt(50));
            }
        } catch (Exception e) {
            throw new RuntimeException("locking error", e);
        }
        return false;
    }

    /**
     * @return void
     * @description 频次限制
     * @params [key, ms, limit]
     * @date 2019/8/19 14:00
     * @author xiaoliang.shang
     **/
    public boolean limit(String key, Long ms, Long limit){
        key = "rate.limiting:" + key;
        Long size=redisTemplate.opsForList().size(key);
        if (size < limit) {
            redisTemplate.opsForList().rightPush(key, String.valueOf(System.currentTimeMillis()));
        } else {
            //最早的
            String time = redisObjectTemplate.opsForList().index(key,0).toString();
            Long now = System.currentTimeMillis();
            log.debug("now {} ,time {}",now,time);
            if (now - Long.valueOf(time) < ms) {
                return false;
            } else {
                redisTemplate.opsForList().rightPush(key,String.valueOf(now));
                redisTemplate.opsForList().trim(key,1,limit);
            }
        }
        return true;
    }





    //自定义
    public static final String REDIS_LOCK_KEY_PREFIX = "MTK_MGT_WEB_LOCK_";
    /**
     * 加锁（自动重试）
     *
     * @param key
     * @param lockKeyType
     * @return
     */
    public boolean tryLock(String key, String lockKeyType) {
        boolean flag = false;
        try {
            key = REDIS_LOCK_KEY_PREFIX + lockKeyType + key;
            log.info("加锁请求数据，key：{}", key);

            long lockTimeout = 500 * 161;
            long sleepTimeout = 500;

            for (int i = 1; i <= 160; i++) {
                flag = this.lockOnce(key, lockTimeout);
                if (flag) {
                    log.info("{}加锁第{}次，成功", key, i);
                    break;
                } else {
//             log.info("{}加锁第{}次，失败", key, i);
                    Thread.sleep(sleepTimeout);
                }
            }
            if (flag) {
                log.info("{}加锁成功", key);
            } else {
                log.info("{}加锁失败", key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 加锁
     * @param key
     * @param lockKeyType
     * @return
     */
    public boolean lock(String key, String lockKeyType) {
        key = REDIS_LOCK_KEY_PREFIX + lockKeyType + key;
        log.info("加锁请求数据，key：{}", key);
        long lockTimeout = 1 * 1000;
        boolean flag = this.lockOnce(key, lockTimeout);
        if (flag) {
            log.info("{}加锁成功", key);
        } else {
            log.info("{}加锁失败", key);
        }
        return flag;
    }

    private boolean lockOnce(String key, long timeout) {
        BoundValueOperations boundValueOperations = this.redisTemplate.boundValueOps(key);
        String value = key + "_"+System.currentTimeMillis();
        Boolean flag = boundValueOperations.setIfAbsent(value); // flag 表示的是否set
        if (flag != null && flag) {
            boundValueOperations.expire(timeout, TimeUnit.MILLISECONDS);
            return true;
        }
        return false;
    }


    /**
     * 版本2.3.3使用
     * @param key
     * @param timeout
     * @return
     */
   /* private boolean lockOnce(String key, long timeout) {
        String value = key + "_"+System.currentTimeMillis();
        boolean flag = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.MILLISECONDS);
        return flag;
    }
    */

    /**
     * 解锁
     *
     * @param key
     * @param lockKeyType
     */
    public void releaseLock(String key, String lockKeyType) {
        key = REDIS_LOCK_KEY_PREFIX + lockKeyType + key;
        log.info("解锁请求数据，key：{}", key);
        try {
            redisTemplate.delete(key);
            log.info("{}解锁成功", key);
        } catch (Exception e) {
            log.error("{}解锁失败，{}", key, e);
        }
    }


}